package org.atguigu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 海晨忆
 * @Des jwt 工具类
 * @Date 2025/8/7 10:32
 */
public class JavaJWTUtils {
    public static final String secret = "fjdskalJFIEWO;2fesd";

    /**
     * 创建JWT
     *
     * @param userJson
     * @return
     */
    public static String createJWT(String userJson) {
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        return JWT.create()
                .withHeader(header)
                .withClaim("user", userJson)
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * 验证JTW
     *
     * @param token
     * @return
     */
    public static boolean verifyToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            //验证没有抛出异常，则验证通过
            DecodedJWT verify = jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 解析JWT数据
     *
     * @param token
     * @return
     */
    public static String parseToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            Claim user = decodedJWT.getClaim("user");
            return user.asString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
